package com.zlp.netty.nio;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

import static com.zlp.netty.buffer.ByteBufferUtil.debugRead;

/**
 * @author: zhulaiping
 * @time: 2022/8/18 17:13
 */
@Slf4j
public class NIOServerDemo1 {

    public static void main(String[] args) throws IOException {
        ByteBuffer buffer = ByteBuffer.allocate(16);
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //serverSocketChannel.configureBlocking(false);
        serverSocketChannel.bind(new InetSocketAddress(8080));
        List<SocketChannel> channels = new ArrayList<>();

        while (true){
            System.out.println("before connecting...");
            // 没有连接时，会阻塞线程
            SocketChannel accept = serverSocketChannel.accept();

            System.out.println("after connecting...");
            channels.add(accept);
            for (SocketChannel channel : channels) {
                //log.debug("before read....{}",channel);
                channel.read(buffer);
                buffer.flip();
                debugRead(buffer);
                buffer.clear();
                //log.debug("after read....{}",channel);
            }
        }
    }
}
